package com.thinkcoder.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thinkcoder.mybatisplusconfig.BaseServiceImpl;
import com.thinkcoder.entity.UserEntity;
import com.thinkcoder.entity.UserToken;
import com.thinkcoder.exception.ServiceException;
import com.thinkcoder.model.constans.ErrorStatus;
import com.thinkcoder.model.constans.TokenConstant;
import com.thinkcoder.util.RedisUtil;
import com.thinkcoder.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements UserService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getToken(String userId,String userPwd) {

        //首先校验用户密码是否正确,用用户id及密码换取token
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("user_pwd",userPwd);
        List<UserEntity> userList = this.list(queryWrapper);
        if(CollectionUtils.isEmpty(userList)){
            throw new ServiceException(ErrorStatus.UNAUTHORIZED.getCode(),ErrorStatus.UNAUTHORIZED.getMessage());
        }

        //校验成功，生成token
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String token = TokenConstant.USER_TOKEN+uuid;
        UserToken userToken = new UserToken();
        userToken.setUserId(userId);
        userToken.setIsOut(0);

        //向redis存入当前用户第一个key
        redisUtil.set(token,userToken,TokenConstant.USER_TOKEN_TIME);

        //拿到上一个用户生成的uuid
        String oldUuid=(String)redisUtil.get(TokenConstant.USER_TOKEN_ID+userId);
        //拼出上一个用户第一个key,拿到用户信息
        UserToken oldUserToken = (UserToken)redisUtil.get(TokenConstant.USER_TOKEN + oldUuid);
        if(oldUserToken!=null){
            //设置用户状态信息为1
            oldUserToken.setIsOut(1);
            //将用户信息存入上一个用户token
            redisUtil.set(TokenConstant.USER_TOKEN+oldUuid,oldUserToken,180);
        }

        //设置当前用户的第二个key
        redisUtil.set(TokenConstant.USER_TOKEN_ID+userId,uuid);
        return token;
    }
}
